import { SuspendedOrders } from './suspendedOrders';
import { PageBase } from 'app/base';
import { ConfigSvr } from './../../services/config';
import { ActivatedRoute, Router } from '@angular/router';
import { ExpeditionOrderDishManage } from './../../components/expeditionOrderDishManage';
import { Orderitem, Order } from './../../models/order';
import { Observable } from 'rxjs/Observable';
import { Subscription, BehaviorSubject } from 'rxjs';
import { AppStore } from './../../services/appStore';
import { routeModel } from './../setup/index';
import { Component, OnInit, OnDestroy, ChangeDetectorRef, ViewChild } from '@angular/core';
import * as R from "ramda"
import { ExpeditionOrderItem, ExpeditionOrder } from './../../models/expeditionOrder';

@Component({
    selector: 'new-home',
    styleUrls: ['./index.scss'],
    template: `
        <div class="pct-h100 cookied_order">
            <div class="inline_four pct-h100">
                <suspended-orders [orders]='orders' [title]="'订单'" [zoneName]="currentZoneName"></suspended-orders>
            </div><div class="inline_two pct-h100">
                <div class="order_box center_part">
                    <div class="top process"> 
                        <div class="order_title">
                        {{order&&order.extended&&order.extended.table&&order.extended.table.zone&&(order.extended.table.zone.name+"-")}}
                        {{order&&order.customerIdentity}}</div>
                        <div class="status">
                            <span>已完成 {{order&&order.hasDeliverCount || 0}} 菜</span>
                            |
                            <span>待出品 {{order&&order.notHasDeliverCount || 0}} 菜</span>   
                        </div>
                        <button class="toggle_btn" (click)="toggleDelivered()">
                            <i class="iconfont icon-transform-expedition"></i>
                            {{(delivered$|async) ? "已完成":"待出品"}}
                        </button>
                    </div>
                    <div class="content status_list">
                        <div class="order_list content_detail columns">
                            <classify-items *ngIf="categorized" [orderItems]="orderItems" [order]="order" [bgColor]="'#fff'"></classify-items>
                            <suspended-orderitems *ngIf = "!categorized" [orderItems]="orderItems" [order]="order"></suspended-orderitems>
                        </div>
                    </div>
                </div>    
            </div><div class="inline_four pct-h100">
                <deliver-orders (zoneNameChange)="onZoneNameChange($event)" [expeditionOrder]="expeditionOrder"></deliver-orders>
            </div>
        </div>
    `
})
export class NewHome extends PageBase implements OnInit, OnDestroy {
    @ViewChild(SuspendedOrders)
    private suspendedOrders: SuspendedOrders;

    
    private orders: Array<Order>;

    currentZoneName:string = "";

    orderItems: Orderitem[]
    delivered$: BehaviorSubject<boolean> = new BehaviorSubject(false);
    order: Order
    delivered = false;

    categorized: boolean;

    expeditionOrder: ExpeditionOrder


    constructor(private changeDetectorRef: ChangeDetectorRef, private activeRouter: ActivatedRoute, private appStore: AppStore, private router: Router, private configSvr: ConfigSvr) {
        super()
    }

    ngOnInit() {
        this.categorized = this.configSvr.orderConfig.categorized;

        const sortByReceivetime = R.sort((x: Order, y: Order) => x.receiveTime - y.receiveTime);
        const expeditionOrderDishItems$ = ExpeditionOrderDishManage.current.observable.map((order => order && order.items || []));
        const orders$ = this.appStore.orderStore.observable.map(orders => sortByReceivetime(orders)).map(orders => {
            orders.forEach(order => order.items = order.items.filter(item => item.isLocalStall));
            return orders;
        });
        const ordersSubscribetion = orders$.subscribe(orders => {
            if (!(this.orders && this.orders.length) && orders[0]) {
                this.router.navigate(["newHome/" + orders[0].id])
            }
            this.orders = orders;
            this.appStore.gloablStore.actions.changeProduceInfo({ orders })
        })
        this.subscribetions.push(ordersSubscribetion);


        const getCount = (status: boolean, order: Order) => {
            const items = order.items.filter(x => Boolean(x.deliverTime) == status);
            return items.map(x => x.qty - (x.refundQty || 0)).reduce((x, y) => x + y, 0);
        }
        const getNotBeDeliverTimedCount = R.curry(getCount)(false);
        const getDeliverTimedCount = R.curry(getCount)(true);

        const paramsId$ = this.activeRouter.params.map(params => params["id"])
        const combinedSubscription = Observable.combineLatest(orders$, paramsId$, expeditionOrderDishItems$, this.delivered$)
            .subscribe(([orders, paramsId, expeditionOrderItems, delivered]) => {
                const orderId = paramsId;
                const order = (<any>orders).find(x => x.id == orderId);
                if (!order) {
                    this.orderItems = [];
                    this.order = null
                    return;
                }
                order.hasDeliverCount = getDeliverTimedCount(order);
                order.notHasDeliverCount = getNotBeDeliverTimedCount(order);
                this.order = order;
                const prediction = delivered ? item => item.qty&&item.deliverTime : (item => item.qty&&!item.deliverTime);
                const items = this.order && this.order.items && this.order.items.filter(prediction);

                this.orderItems = items && items.filter(item => {
                    return !expeditionOrderItems.find(iitem => iitem.kitchenOrderItemId == item.id)
                });
                // this.changeDetectorRef.detectChanges();
            })
        this.subscribetions.push(combinedSubscription);
        const expeditionOrderDish$ = ExpeditionOrderDishManage.current.observable;
        const subscription = expeditionOrderDish$.subscribe(expeditionOrder => {
            if(this.expeditionOrder&&this.expeditionOrder.serialNo!=(expeditionOrder&&expeditionOrder.serialNo)){
                setTimeout(() => {
                    if(this.orderItems&&this.orderItems.length==0){
                        this.suspendedOrders.navigatFirstView();
                    }
                }, 5);
            }
            this.expeditionOrder = JSON.parse(JSON.stringify(expeditionOrder));
        })
        this.subscribetions.push(subscription);
    }

    toggleDelivered() {
        this.delivered = !this.delivered;
        this.delivered$.next(this.delivered)
    }

    onZoneNameChange(zoneName){
        this.currentZoneName = zoneName;
        this.changeDetectorRef.detectChanges();
        if(this.currentZoneName){
            this.suspendedOrders.navigatSecendView();
        } else {
            this.suspendedOrders.navigatFirstView();
        }
    }
}


